<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <!-- 收获地址 -->
    <van-contact-card type="edit" :tel="address.tel" :name="`${address.name}(${address.region_text})`" v-if="address"
        @click="AddressChange" />
    <van-contact-card type="add" v-else @click="AddressAdd" />

    <van-checkbox-group v-model="checked" ref="checkboxGroup">
        <div class="cart" v-for="(item, key) in list" :key="key">
            <!-- 商品卡片 -->
            <van-card :price="item.total" :desc="'库存：' + item.product.stock" :title="item.product.name"
                :thumb="item.product.thumbs_text" :num="item.nums" @click-thumb="toProductInfo(item.proid)">
                <!-- 卡片的插槽部分 -->
                <template #desc v-if="item.attrs">
                    <van-tag v-for="(value, index) in item.attrs" :key="index" type="primary">{{
                        value.value }}</van-tag>
                </template>

                <template #desc v-else>
                    <van-tag type="danger">无规格商品</van-tag>
                </template>
            </van-card>
        </div>
    </van-checkbox-group>

    <!-- 单元格 -->
    <van-cell title="支付方式" is-link :value="PayActive.text" @click="PayShow = true" />
    <!-- 支付方式选择器 -->
    <van-popup v-model:show="PayShow" position="bottom" :style="{ height: '30%' }">
        <van-picker title="支付方式" :columns="PayList" @cancel="PayShow = false" @confirm="PayConfirm" />
    </van-popup>

    <!-- 优惠券单元格 -->
    <van-coupon-cell :coupons="CouponList" :chosen-coupon="CouponActive" @click="CouponShow = true" />
    <!-- 优惠券列表 -->
    <van-popup v-model:show="CouponShow" round position="bottom" style="height: 52%; padding-top: 4px;">

        <van-coupon-list :coupons="CouponList" :chosen-coupon="CouponActive" :show-exchange-bar="false"
            @change="onChange" />
    </van-popup>


    <!--订单备注 -->
    <van-field v-model="remark" rows="2" autosize label="订单备注" type="textarea" maxlength="120" placeholder="请输入订单备注"
        show-word-limit />

    <!-- 提交动作栏 -->
    <van-submit-bar text-align="left" :price="total" button-text="确认支付" @submit="onSubmit" />
</template>

<script setup>
import { computed, getCurrentInstance, onBeforeMount, ref } from 'vue'

const { proxy } = getCurrentInstance()

// 获取购物车 ids
const cartids = proxy.$route.query.cartids ?? '0'

// 响应式数据
const checked = ref([])
const list = ref([])
const address = ref(null)
const remark = ref('')

// 支付方式
const PayShow = ref(false)
const PayActive = ref({ text: '余额', value: 'money' })
const PayList = ref([
    { text: '余额', value: 'money' },
    { text: '微信', value: 'wx' },
    { text: '支付宝', value: 'zfb' },
])

// 优惠券

const CouponList = ref([]);
const CouponShow = ref(false);
const CouponActive = ref(-1);


// 生命周期
onBeforeMount(() => {
    CartInfo()
    AddressInfo()
    CouponInfo()
})

// 购物车数据
const CartInfo = async () => {
    // 组装数据
    var params = {
        busid: proxy.$business.value.id,
        cartids
    }

    var result = await proxy.$POST({
        url: '/cart/index',
        params
    })

    if (result.code == 0) {
        proxy.$fail(result.msg)
        return false
    }

    result.data.map(item => item.attrs = JSON.parse(item.attrs))

    list.value = result.data

    // console.log(list.value)

}

// 返回收获地址方法
const AddressInfo = async () => {
    // 先判断cookie中是否存在缓存
    var cached = proxy.$cookies.get('address') ?? null

    if (cached) {
        address.value = cached
    } else {
        var result = await proxy.$POST({
            url: '/address/selected',
            params: { busid: proxy.$business.value.id }
        })

        if (result.code == 0) {
            proxy.$fail(result.msg)
            return false
        }

        address.value = result.data

        // console.log(address.value)
    }

}

// 切换收获地址
const AddressChange = () => {
    proxy.$router.push({ path: '/address/index', query: { action: 'select' } })
}

// 添加收获地址
const AddressAdd = () => {
    proxy.$router.push('/address/add')
}

//跳转到商品详情界面
const toProductInfo = pid => proxy.$router.push({ path: '/product/info', query: { pid } })

// 支付方式
const PayConfirm = ({ selectedOptions }) => {
    PayShow.value = false
    PayActive.value = selectedOptions[0]
}

// 返回优惠券方法
const CouponInfo = async () => {
    var result = await proxy.$POST({
        url: '/business/coupon',
        params: { busid: proxy.$business.value.id }
    })


    if (result.code && result.data.length > 0) {
        var coupons = []

        for (var item of result.data) {
            coupons.push({
                available: item.id,
                condition: `无门槛\n${item.coupon.status_text}`,
                rate: item.coupon.rate,
                name: item.coupon.title,
                startAt: item.coupon.createtime,
                endAt: item.coupon.endtime,
                valueDesc: item.coupon.rate * 100,
                unitDesc: '折',
            })
        }
    }
    CouponList.value = coupons
}

// 选择优惠券
const onChange = (index) => {
    var total = 0
    list.value.map((item) => total += parseFloat(item.total))

    CouponShow.value = false;

    if (index != -1) {
        // 计算优惠额
        const Rate = CouponList.value[index].rate
        const price = total * Rate
        const CouponPrice = parseFloat(total - price).toFixed(2)

        CouponList.value[index].value = CouponPrice * 100
    }

    CouponActive.value = index;
}

//合计的价格
const total = computed(() => {
    var total = 0
    list.value.map((item) => total += parseFloat(item.total))

    if (CouponActive.value != -1) {
        const rate = CouponList.value[CouponActive.value].rate
        total = (total * rate).toFixed(2)
    }
    return parseFloat(total * 100)
})

// 确认订单
const onSubmit = async () => {
    // 组装数据
    var params = {
        busid: proxy.$business.value.id,
        addrid: address.value.id,
        cartids,
        remark: remark.value,
        pay: PayActive.value.value
    }

    if (CouponActive.value != -1) {
        params.couponid = CouponList.value[CouponActive.value].available
    }

    var result = await proxy.$POST({
        url: '/order/add',
        params
    })

    proxy.$success({
        message: result.msg,
        onClose: () => {
            // proxy.$router.push(result.url)
            proxy.$router.push('/business/index')
        }
    })
}
</script>

<style scoped>
:deep(.cart) {
    display: flex;
    width: 100%;
}

::v-deep .van-swipe-cell {
    width: 100%;
}

.van-card {
    background-color: transparent;
}

.delete-button {
    height: 100%;
}

.van-tag {
    margin-right: 5px;
}
</style>